﻿using BaoVeThanhDia.Buttons;
using BaoVeThanhDia.Introduction;
using BaoVeThanhDia.Sound;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using NapThe;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Navigation;

namespace BaoVeThanhDia.MapAndUpgrade
{
    public partial class MapAndUpgrade : PhoneApplicationPage
    {
        UIElementRenderer elementRenderer;
        public static ContentManager contentManager;
        public static int LevelSelected;
        private GameTimer timer;
        private SpriteBatch spriteBatch;
        private string trangthai; // trạng thái selectMap or upgrade
        private Texture2D BackGround; // ảnh nền
        private List<Button> buttons; //các button
        private Vector2 start, curtouch, Dolech;
        private UpgradeInterface upgradeInterface;
        private MapInterface mapInterface;
        private bool isZoom;
        private int countZoom;
        private float scale;
        private CustomSoundEffect click;
        private BackgroundWorker bw = new BackgroundWorker();

        public static NapXu napxu;
        private bool isLoaded;
        SpriteFont font;

        public MapAndUpgrade()
        {
            InitializeComponent();
            contentManager = (Application.Current as App).Content;
            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;
            LayoutUpdated += new EventHandler(XNARendering_LayoutUpdated);
            //todo
            #region OGG
            isLoaded = false;
            bw.WorkerReportsProgress = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            bw.RunWorkerAsync();
            #endregion

            click = new CustomSoundEffect("sounds/effect/Click_Button");
            trangthai = "map";
            buttons = new List<Button>();
            buttons.Add(new Button("", "images/mapandupgrade/bar", new Vector2(0, 420), new Vector2(0, 0), new Vector2(200, 15), 4));
            buttons.Add(new Button("nangcap", "images/mapandupgrade/nangcap", new Vector2(530, 400), new Vector2(0, 0), new Vector2(117, 99), 0.75f));
            buttons.Add(new Button("gioithieu", "images/mapandupgrade/gioithieu", new Vector2(650, 400), new Vector2(0, 0), new Vector2(124, 95), 0.75f));
            buttons.Add(new Button("trolai", "images/Introduction/trolai", new Vector2(10, 420), new Vector2(0, 0), new Vector2(228, 100), 0.6f));

            napxu = new NapXu(LayoutRoot);
        }
        void XNARendering_LayoutUpdated(object sender, EventArgs e)
        {
            // make sure page size is valid
            if (ActualWidth == 0 || ActualHeight == 0)
                return;

            // see if we already have the right sized renderer
            if (elementRenderer != null &&
                elementRenderer.Texture != null &&
                elementRenderer.Texture.Width == (int)ActualWidth &&
                elementRenderer.Texture.Height == (int)ActualHeight)
            {
                return;
            }

            // dispose the current renderer
            if (elementRenderer != null)
                elementRenderer.Dispose();

            // create the renderer
            elementRenderer = new UIElementRenderer(this, (int)ActualWidth, (int)ActualHeight);
        }
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            // Perform a time consuming operation and report progress.
            // System.Threading.Thread.Sleep(50);
            //   worker.ReportProgress()
            AudioManager.LoadSounds("song_selectmap.ogg");
        }
        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            isLoaded = true;
            if (MainPage.isNen) AudioManager.PlaySound("song_selectmap.ogg", true);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            // TODO: use this.content to load your game content here
            if (MenuIntroduction.contentManager != null) MenuIntroduction.contentManager.Unload();
            if (GamePage.contentManager != null) GamePage.contentManager.Unload();
            if (MainPage.contentManager != null) MainPage.contentManager.Unload();
            click.Load(contentManager);
            File_Upgrade_Star.getData();
            mapInterface = new MapInterface();
            upgradeInterface = new UpgradeInterface();
            isZoom = false;
            Dolech = new Vector2(0, 0);
            countZoom = 0;
            scale = 1.0f;
            foreach (Button button in buttons)
            {
                button.Load(contentManager);
            }
            mapInterface.Load(contentManager);
            upgradeInterface.Load(contentManager);
            if (MainPage.isNen) AudioManager.PlaySound("song_selectmap.ogg", true);
            font = contentManager.Load<SpriteFont>("fonts/WaveFont");
            timer.Start();

            base.OnNavigatedTo(e);
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);
            AudioManager.StopSound("song_selectmap.ogg");
            base.OnNavigatedFrom(e);
        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            click.Play();
            if (!napxu.isVisible())
            {
                if (!trangthai.Equals("map"))
                {
                    trangthai = "map";
                    Dolech = new Vector2(0, 0);
                    isZoom = false;
                    countZoom = 0;
                    scale = 1;
                    e.Cancel = true;
                }
            }
            else
            {
                napxu.Collapsed();
                e.Cancel = true;
            }
        }
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            // TODO: Add your update logic here
            if (isLoaded)
            {
                if (isZoom)
                {
                    if (countZoom < 100) countZoom += 3;
                }
                TouchCollection touchs = TouchPanel.GetState();
                foreach (TouchLocation touch in touchs)
                {
                    if (touch.State == TouchLocationState.Pressed)
                    {
                        start = touch.Position;
                        curtouch = touch.Position;
                    }
                    if (touch.State == TouchLocationState.Moved)
                    {
                        #region sự kiện vuốt7
                        if (!napxu.isVisible())
                            Dolech += touch.Position - curtouch;
                        curtouch = touch.Position;
                        if (trangthai.Equals("upgrade"))
                        {
                            Dolech.X = 0;
                            if (Dolech.Y > 0) Dolech.Y = 0;
                            if (-Dolech.Y + 480 > 1040) Dolech.Y = 480 - 1040;
                        }
                        else
                        {
                            if (Dolech.X > 0) Dolech.X = 0;
                            if (Dolech.Y > 0) Dolech.Y = 0;
                            if (-Dolech.X + 800 > 800 * scale) Dolech.X = 800 * (1 - scale);
                            if (-Dolech.Y + 420 > 420 * scale) Dolech.Y = 420 * (1 - scale);
                        }
                        #region hiệu ứng nổi lên khi vuốt qua button
                        if (trangthai.Equals("map"))
                        {
                            foreach (Button button in buttons)
                            {
                                if (!button.getName().Equals(""))
                                {
                                    button.isTouch(curtouch);
                                }
                            }
                        }
                        else
                        {
                            if (!napxu.isVisible())
                                upgradeInterface.isTouch(curtouch, Dolech);
                        }
                        #endregion
                        #endregion
                    }
                    if (touch.State == TouchLocationState.Released)
                    {
                        curtouch = touch.Position;
                        if (trangthai.Equals("map"))
                        {
                            #region khi đang lựa chọn map
                            if (curtouch.Y < 420)
                            {
                                if (!isZoom)
                                {
                                    isZoom = true;
                                    countZoom = 0;
                                }
                                else
                                {
                                    if (Vector2.Distance(curtouch, start) < 50)
                                    {
                                        if (mapInterface.isTouch(curtouch, Dolech, scale, true) != -1)
                                        {
                                            click.Play();
                                            LevelSelected = mapInterface.isTouch(curtouch, Dolech, scale);
                                            if (FileThanh.isOpens[LevelSelected])
                                                NavigationService.Navigate(new Uri("/../GamePage.xaml", UriKind.Relative));
                                        }
                                    }
                                }
                            }
                            foreach (Button button in buttons)
                            {
                                if (!button.getName().Equals(""))
                                {
                                    if (button.isTouch(curtouch))
                                    {
                                        click.Play();
                                        button.setTouch(false);
                                        if (Vector2.Distance(curtouch, start) < 50)
                                        {
                                            if (button.getName().Equals("trolai"))
                                            {
                                                NavigationService.GoBack();
                                            }
                                            else if (button.getName().Equals("nangcap"))
                                            {
                                                trangthai = "upgrade";
                                                Dolech = new Vector2(0, 0);
                                            }
                                            else
                                            {
                                                NavigationService.Navigate(new Uri("/../Introduction/MenuIntroduction.xaml", UriKind.Relative));
                                            }
                                        }
                                    }
                                }
                            }
                            #endregion
                        }
                        else
                        {
                            #region khi đang trong nâng cấp
                            if (upgradeInterface.isTouch(curtouch, Dolech, contentManager, napxu))
                            {
                                if (Vector2.Distance(curtouch, start) < 50)
                                {
                                    click.Play();
                                    trangthai = "map";
                                    Dolech = new Vector2(0, 0);
                                    isZoom = false;
                                    countZoom = 0;
                                    scale = 1;
                                }
                            }
                            #endregion
                        }
                    }
                }
            }
        }
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.CornflowerBlue);
            elementRenderer.Render();
            if (trangthai.Equals("map"))
            {
                BackGround = contentManager.Load<Texture2D>("images/mapandupgrade/map");
            }
            else
            {
                BackGround = contentManager.Load<Texture2D>("images/mapandupgrade/bgupgrade");
            }
            // TODO: Add your drawing code here
            spriteBatch.Begin();
            if (isLoaded)
            {
                if (isZoom)
                {
                    scale = 1 + countZoom * 0.01f;
                }
                spriteBatch.Draw(BackGround, trangthai.Equals("map") ? new Vector2(0, 0) + Dolech : new Vector2(0, 0), new Rectangle(0, 0, (trangthai.Equals("map") ? 800 : 200), (trangthai.Equals("map") ? 480 : 120)), Color.White, 0f, Vector2.Zero, (trangthai.Equals("map") ? (isZoom ? scale : 1) : 4), SpriteEffects.None, 0f);
                if (trangthai.Equals("map"))
                {
                    mapInterface.Draw(spriteBatch, Dolech, scale);
                    foreach (Button button in buttons)
                    {
                        button.Draw(spriteBatch, new Vector2(0, 0));
                    }
                }
                else
                {
                    upgradeInterface.Draw(contentManager, spriteBatch, Dolech, napxu);
                }
                spriteBatch.Draw(elementRenderer.Texture, Vector2.Zero, Color.White);
            }
            else
            {
                spriteBatch.Draw(BackGround, trangthai.Equals("map") ? new Vector2(0, 0) + Dolech : new Vector2(0, 0), new Rectangle(0, 0, (trangthai.Equals("map") ? 800 : 200), (trangthai.Equals("map") ? 480 : 120)), Color.White, 0f, Vector2.Zero, (trangthai.Equals("map") ? (isZoom ? scale : 1) : 4), SpriteEffects.None, 0f);
                spriteBatch.DrawString(font, "Loading . . .", new Vector2(630, 450), Color.White);
            }
            spriteBatch.End();
        }
    }
}